package com.diandiansong.app.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.diandiansong.app.R;
import com.diandiansong.app.entity.SearchInfo;
import com.diandiansong.app.ui.commonlist.SearchList;
import com.diandiansong.app.utils.A;
import com.diandiansong.app.widgets.SearchView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import diandiansong.library.ui.base.BaseAct;
import diandiansong.library.ui.base.FastListFragment;
import diandiansong.library.utils.BaseEntity;
import diandiansong.library.utils.CCallBack;
import diandiansong.library.widgets.FlowLayout;

/***
 * 搜索
 */
public class Search extends BaseAct {

    public static void start(Context context) {
        Intent starter = new Intent(context, Search.class);
        context.startActivity(starter);
    }

    EditText mSearchInput;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initTitle("");

        SearchView searchView = findViewById(R.id.title_search_view);
        searchView.setVisibility(View.VISIBLE);
        mSearchInput = searchView.getEditText();

        mSearchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {

                    // 当按了搜索之后关闭软键盘
                    ((InputMethodManager) mSearchInput.getContext().getSystemService(
                            Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                            getActivity().getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS
                    );

                    String keywords = mSearchInput.getText().toString().trim();
                    SearchList.start(getActivity(), keywords);
                    mSearchInput.setText("");

                    return true;
                }
                return false;
            }
        });

        addFragment(SubFragment.class.getName());
    }

    @Override
    protected void onResume() {
        super.onResume();
        SubFragment.doRefresh();
    }

    public static class SubFragment extends FastListFragment<String> {


        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            EventBus.getDefault().register(this);
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            EventBus.getDefault().unregister(this);
        }

        FlowLayout mFlTags;
        TextView mDoClearHis;


        /**
         * 允许子类重写，替换布局
         * <p/>
         * must have @id/swiperefreshlayout @id/listview
         *
         * @return layoutId
         */
        @Override
        protected int getLayoutId() {
            return R.layout.search;
        }

        /**
         * viewCreated 后调用
         *
         * @param rootView framentView
         */
        @Override
        public void initView(View rootView) {
            mFlTags = rootView.findViewById(R.id.fl_tags);
            mDoClearHis = rootView.findViewById(R.id.do_clear_his);
            mDoClearHis.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onLoading();
                    A.commoditySearch_del(new CCallBack<BaseEntity>() {
                        @Override
                        public void onSuccess(BaseEntity baseEntity) throws Exception {
                            onLoaded();
                            mAdapter.clear();
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            onLoaded();
                            toast(msg);
                        }
                    });
                }
            });
        }

        @Override
        public int getItemLayoutRes() {
            return R.layout.search_item;
        }

        @Override
        public void bindItemView(int position, @NonNull View convertView) {
            TextView textView = findViewById(convertView, R.id.tv_1);
            textView.setText(getItem(position));
        }

        /**
         * 滑到底部时调用
         */
        @Override
        protected void loadMore() {
            A.commoditySearch_record(new CCallBack<SearchInfo>() {
                @Override
                public void onSuccess(SearchInfo searchInfo) throws Exception {
                    mFlTags.removeAllViews();
                    List<String> hotKey = searchInfo.getData().getHotKey();
                    for (final String item : hotKey) {
                        View tagView = LayoutInflater.from(getActivity()).inflate(R.layout.search_tag, null);
                        tagView.setLayoutParams(new ViewGroup.MarginLayoutParams(new ViewGroup.LayoutParams(
                                ViewGroup.LayoutParams.WRAP_CONTENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT
                        )));
                        TextView textView = tagView.findViewById(R.id.tv_1);
                        textView.setText(item);

                        tagView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                SearchList.start(getActivity(), item);
                            }
                        });
                        mFlTags.addView(tagView);


                        mAdapter.setData(searchInfo.getData().getHistoricalRecords());
                        onLoadFinishNoMore();
                    }
                }

                @Override
                public void onFailure(int code, String msg) {
                    toast(msg);
                }
            });
        }

        @Override
        public void onItemClick(String s) {
            super.onItemClick(s);
            SearchList.start(getActivity(), s);
        }


        public static class Refresh {
        }

        public static void doRefresh() {
            EventBus.getDefault().post(new Refresh());
        }

        @Subscribe(threadMode = ThreadMode.MAIN)
        public void receiceRefresh(Refresh refresh) {
            refresh();
        }
    }
}
